package com.hong.spring.listener;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hong.spring.api.IUserService;
import com.hong.spring.entity.User;
import com.hong.spring.utils.DataResponse;
import com.rabbitmq.client.Channel;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;
import org.springframework.amqp.rabbit.core.ChannelAwareMessageListener;
import org.springframework.amqp.rabbit.listener.adapter.MessageListenerAdapter;
import org.springframework.amqp.utils.SerializationUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Objects;

/**
 * @author: csh
 * @Date: 2021/3/16 11:14
 * @Description:用户监听
 */
@Log4j2
public class UserListener extends MessageListenerAdapter {

    @Autowired
    private IUserService userService;


    public void onMessage(Message message, Channel channel) throws Exception {
        try {
            log.info("添加用户参数{}",JSONObject.toJSONString(message));
            String messageBody = new String(message.getBody());
            ObjectMapper mapper=new ObjectMapper();
            User user = mapper.readValue(messageBody.getBytes("UTF-8"),User.class);
            log.info("获取的用户信息{}", JSONObject.toJSONString(user));
            DataResponse<Boolean> save = userService.save(user);
            if(save==null || save.getData()==null || !save.getData()){
                log.info("添加失败，原因{}",JSONObject.toJSONString(save));
            }
        }catch (Exception e){
            log.error("添加用户异常{}",e);
        }
    }

    public static void main(String[] args) {
        System.out.println(Objects.equals(null,1));
    }
}
